﻿using System;
using System.Collections.Generic;

namespace zTalk.Network
{
    public class PacketReader
    {
        public static IPacketHandler Handler;

        private List<byte> buffer = new List<byte>();
        private Packet packet = new Packet();

        public void ReadData(SocketBase client, byte[] bytes)
        {
            buffer.AddRange(bytes);

            while (true)
            {
                if (buffer.Count >= 1 && packet.Opcode == Opcodes.NONE)
                {
                    packet.Opcode = (Opcodes)buffer[0];
                }
                if (buffer.Count >= Packet.HEADER_LENGTH && packet.Length == 0)
                {
                    packet.Length = BitConverter.ToInt32(
                        new byte[] { 
                            buffer[1], buffer[2], 
                            buffer[3], buffer[4] }, 0);
                }

                if (buffer.Count >= packet.Length + Packet.HEADER_LENGTH)
                {
                    byte[] data = new byte[packet.Length];
                    Array.Copy(buffer.ToArray(), Packet.HEADER_LENGTH, 
                        data, 0, packet.Length);
                    packet.Data = data;

                    buffer.RemoveRange(0, packet.Length + Packet.HEADER_LENGTH);

                    Handler.Handle(client, packet);

                    // reset packet
                    packet = new Packet();
                }
                else
                {
                    break;
                }
            }
        }
    }
}